package com.xjscrm.console.chat.core.impl.conversation;

import com.alibaba.fastjson.JSON;
import com.xjscrm.common.entity.WwGroup;
import com.xjscrm.common.entity.WwGroupMember;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.console.chat.core.ChatBaseMsgHandler;
import com.xjscrm.console.chat.enums.ChatMsgType;
import com.xjscrm.console.chat.frame.dto.ChatTagDTO;
import com.xjscrm.console.chat.frame.recv.RPullGroupConversationInfoMsg;
import com.xjscrm.console.chat.frame.send.SPullGroupConversationResultMsg;
import com.xjscrm.console.chat.frame.send.SResultMsg;
import com.xjscrm.console.entity.ChatTalkSession;
import com.xjscrm.console.mapper.WwGroupMemberMapper;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
import com.xjscrm.console.service.customer.group.WwGroupService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author mingyang.chen create in 2024/3/17 09:42
 */
@Component
@Slf4j
public class ChatPullGroupConversationInfoMsgHandler extends ChatBaseMsgHandler<RPullGroupConversationInfoMsg> {

    @Autowired
    private WwGroupService wwGroupService;
    @Autowired
    private ChatTalkSessionService chatTalkSessionService;
    @Autowired
    private WwGroupMemberMapper wwGroupMemberMapper;

    @Override
    public Class<RPullGroupConversationInfoMsg> msgClass() {
        return RPullGroupConversationInfoMsg.class;
    }

    @Override
    public boolean checkMsg(RPullGroupConversationInfoMsg baseMsg) {
        return super.checkMsg(baseMsg) || !ObjectUtils.isNotEmpty(baseMsg.getTalkSessionId());
    }

    @Override
    public SResultMsg doHandle(RPullGroupConversationInfoMsg content, ChannelHandlerContext ctx) {

        Long merId = content.getMerId();


        ChatTalkSession byId = chatTalkSessionService.getById(merId, content.getTalkSessionId());
        if (Objects.isNull(byId)) {
            throw new BusinessException("获取群资料失败: 会话不存在");
        }
        WwGroup byGroupId = wwGroupService.getByGroupId(byId.getMerId(), byId.getDeviceUniqueId(), byId.getConversationId());
        if (Objects.isNull(byGroupId)) {
            throw new BusinessException("获取群资料失败: 群聊不存在");
        }

        SPullGroupConversationResultMsg pullGroupConversationResultMsg = new SPullGroupConversationResultMsg();
        //
        chatTalkSessionService.fillTag(byId, tag -> {
            ChatTagDTO chatTagDTO = new ChatTagDTO(tag.getId(), tag.getTagName());
            pullGroupConversationResultMsg.getTags().add(chatTagDTO);
        }, tag1 -> {
            ChatTagDTO chatTagDTO = new ChatTagDTO(tag1.getId(), tag1.getName());
            pullGroupConversationResultMsg.getTags().add(chatTagDTO);
        });

        //
        String createWxid = byGroupId.getCreateWxid();
        String r = byGroupId.getAdminWxIds();
        if (StringUtils.isNotBlank(r)) {
            try {
                List<String> adminWxIds = JSON.parseArray(r, String.class);
                if (ObjectUtils.isNotEmpty(adminWxIds)) {
                    adminWxIds.add(createWxid);
                }
                //
                List<WwGroupMember> groupMembers = wwGroupMemberMapper.selectListByGroupWxIdAndWxid(byGroupId.getGroupWxid(), adminWxIds, merId);
                adminWxIds.remove(createWxid);
                if (ObjectUtils.isNotEmpty(groupMembers)) {
                    Map<String, WwGroupMember> collect = groupMembers.stream().collect(Collectors.toMap(WwGroupMember::getWxid, Function.identity()));

                    for (String adminWxId : adminWxIds) {
                        WwGroupMember wwGroupMember = collect.get(adminWxId);

                        SPullGroupConversationResultMsg.GroupAdminItem groupAdminItem = new SPullGroupConversationResultMsg.GroupAdminItem();
                        groupAdminItem.setAdminWxName(wwGroupMember.getNick());
                        groupAdminItem.setAdminWxId(wwGroupMember.getWxid());
                        groupAdminItem.setHeadImageUrl(wwGroupMember.getHimg());

                        pullGroupConversationResultMsg.getAdmins().add(groupAdminItem);
                    }

                    WwGroupMember createGroupMember = collect.get(createWxid);
                    if (Objects.nonNull(createGroupMember)) {
                        pullGroupConversationResultMsg.setCreateWxName(createGroupMember.getNick());
                    }
                }
            } catch (Exception e) {
                log.error("解析群管理员json出错");
            }
        }

        return pullGroupConversationResultMsg;
    }

    @Override
    public ChatMsgType msgType() {
        return ChatMsgType.r_pull_group_conversation_info;
    }
}
